<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 考试管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection"
                    v-if="false">批量删除</el-button>
                <el-select v-model="query.exam_type" placeholder="考试类型" @change="addSearchFunc2" class="handle-select mr10">
                    <el-option key="1" label="全部" value="全部"></el-option>
                    <el-option key="2" label="完成公开" value="完成公开"></el-option>
                    <el-option key="3" label="不公开" value="不公开"></el-option>
                </el-select>
                <el-input v-model="query.name" @input="addSearchFunc" placeholder="搜索考试名称"
                    class="handle-input mr10"></el-input>
            </div>
            <div style="margin-bottom:20px;">
                <el-button type="primary" icon="el-icon-add" @click="dialogFormVisible = true">
                    <i class="el-icon-lx-add"></i>
                    <span>添加</span>
                </el-button>

                <el-button type="danger" plain icon="el-icon-add" @click="delAllSelection">
                    <i class="el-icon-lx-delete"></i>
                    <span>删除</span>
                </el-button>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="topic_lib_name" label="题库名称"></el-table-column>
                <el-table-column prop="topic_type" label="题目类型"></el-table-column>
                <el-table-column prop="exam_type" label="考试类型"></el-table-column>
                <el-table-column prop="topic_content" label="题目内容"></el-table-column>
                <el-table-column prop="user_name" label="创建人"></el-table-column>
            </el-table>

            <div style="margin-top:20px;">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
                </el-pagination>
            </div>


            <el-dialog title="添加试题" :visible.sync="dialogFormVisible">
                <el-form :model="form">
                    <el-form-item label="题目类型" :label-width="formLabelWidth">
                        <el-select v-model="form.topic_type" placeholder="请选择题目类型" @change="addTopicTypeFunc">
                            <el-option label="单选题" value="单选题"></el-option>
                            <el-option label="多选题" value="多选题"></el-option>
                            <el-option label="判断题" value="判断题"></el-option>
                        </el-select>
                        
                    </el-form-item>
                       
                    <el-form-item label="题型数量" :label-width="formLabelWidth">
                        <p><span>【{{topic_current_num}}/{{topic_total_num}}】</span></p>
                    </el-form-item>

                    <el-form-item label="归属题库" :label-width="formLabelWidth">
                        <el-select v-model="form.topic_lib_name" placeholder="请选择题库名称" @change="getCurrentTopicLibInfo">
                            <el-option v-for="libItem in topicLibs" :label="libItem.topic_lib_name"
                                :value="libItem.topic_lib_name"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="题目内容" :label-width="formLabelWidth">
                        <el-input type="textarea" v-model="form.topic_content"></el-input>
                    </el-form-item>

                    <el-form-item label="整题解析" :label-width="formLabelWidth">
                        <el-input type="textarea" v-model="form.topic_analysis"></el-input>
                    </el-form-item>

                    <el-form-item label="题目分值" :label-width="formLabelWidth">
                        <el-input type="number" v-model="form.topic_val"></el-input>
                    </el-form-item>

                    <!-- 添加题目 -->
                    <el-form-item>
                        <el-button plain type="primary" icon="el-icon-add" @click="addOptionFunc">
                            <i class="el-icon-lx-add"></i>
                            <span>添加</span>
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <template>
                            <el-table :data="form.options" border class="table" ref="multipleTable"
                                header-cell-class-name="table-header" @selection-change="handleSelectionChange5">
                                <el-table-column type="selection" width="55" align="center"></el-table-column>

                                <el-table-column label="答案选项">
                                    <template slot-scope="scope">
                                        <el-input type="textarea" v-model="scope.row.opt" placeholder=""></el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column label="答案内容">
                                    <template slot-scope="scope">
                                        <el-input type="textarea" v-model="scope.row.text" placeholder=""></el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column label="答案解析">
                                    <template slot-scope="scope">
                                        <el-input type="textarea" v-model="scope.row.desc" placeholder=""></el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column label="操作" width="100" align="center">
                                    <template slot-scope="scope">
                                        <el-button @click="removeCurrentTopic(scope.$index)" type="danger"
                                            icon="el-icon-delete" circle></el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                        </template>

                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addTopicFunc">确 定</el-button>
                </div>
            </el-dialog>
        </div>

        <!-- 编辑弹出框 -->
        <!-- <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog> -->
    </div>
</template>

<script>
import { topicAdd, topicList, topicTotal, getTopicLibPublish, topicRemove, topicSearch, topicTypeTotal } from '../../api/index';
export default {
    name: 'examinationmanagement',
    data() {
        return {
            query: {
                exam_type: '',
                name: '',
                pageIndex: 1,
                pageSize: 10,
            },
            tableData: [],
            multipleSelection: [],
            // 记录当前类型题目数量
            topic_current_num: 0,
            topic_total_num: 0,
            delList: [],
            // editVisible: false,
            pageTotal: 0,
            idx: -1,
            id: -1,
            currentPage: 1,
            // 判断该用户是否发布题库
            isHasLib: false,
            // 记录已发布题库
            topicLibs: [],
            // 记录当前题库信息
            currentTopicLibInfo: {},
            // 是否显示弹窗
            dialogFormVisible: false,
            topic_lib_id:'',
            // 表单信息
            form: {
                topic_type: '单选题', // 题目类型
                topic_lib_name: '',// 题库
                topic_content: '',// 题目内容
                topic_analysis: '',//题目解析
                topic_val: 10,//分值
                topic_answer: '',//正确答案
                options: [
                    {
                        opt: '',
                        text: '',
                        desc: ''
                    },
                    {
                        opt: '',
                        text: '',
                        desc: ''
                    }
                ]
            },
            // 选项索引
            optionIndex: 2,
            // label标签宽度
            formLabelWidth: '120px',
            // 记录题目
            multipleSelection2: [],
            tableData5: [],
            multipleSelection5: [],
            formData5: [],
            // 记录需要删除的题目
            topicRemoveArr: [],
            // 记录需要发布的题数量
            topic_single_count: 0,
            topic_multi_count: 0,
            topic_judge_count: 0,

        };
    },
    created() {
        this.getData();
        this.topicLibPublishFunc();
        this.getTotalNum();
    },
    watch: {
        // form:{
        //     deep: true,
        //     immediate: true,
        //     handler(val) {
        //         // console.log('testxxx')
        //         let topic_type = val.topic_type;
        //         let topic_lib_id = this.topic_lib_id;
        //         this.topicTypeTotalFunc(topic_lib_id, topic_type);
        //     }
        // },
        // $route: {
        //     deep: true,
        //     immediate: true,
        //     handler() {
        //         // console.log('testxxx')
        //         // this.topicLibPublishFunc();
        //     }
        // }
    },
    methods: {
        // user_name, topic_type, topic_content, topic_analysis, exam_time, exam_type, topic_lib_id,topic_options,topic_val
        // 添加题目
        async addTopicFunc() {
            // 判断该用户是否发布题库了
            if (this.isHasLib) {
                let user_name = localStorage.getItem('user_name');
                let { exam_time, exam_type, topic_lib_id, topic_lib_name } = this.currentTopicLibInfo;
                this.topic_lib_id = topic_lib_id;
                let { topic_type, topic_content, topic_analysis, options, topic_val, topic_answer } = this.form;
                let topic_options = JSON.stringify(options);
                // console.log({user_name, topic_type, topic_content, topic_analysis, exam_time, exam_type, topic_lib_id,topic_options,topic_val,topic_answer,topic_lib_name});
                await topicAdd({ user_name, topic_type, topic_content, topic_analysis, exam_time, exam_type, topic_lib_id, topic_options: JSON.stringify(topic_options), topic_val, topic_answer, topic_lib_name })
                    .then(
                        content => {
                            // console.log('添加题目成功:', content);
                            let { code, msg } = content;
                            if (code == 200) {
                                this.$message({
                                    message: msg,
                                    type: 'success'
                                })
                                this.dialogFormVisible = false;
                                this.getData();
                                this.getTotalNum();
                                // 重置表单
                                this.form = {
                                    topic_type: '单选题', // 题目类型
                                    // topic_lib_name: '',// 题库
                                    topic_content: '',// 题目内容
                                    topic_analysis: '',//题目解析
                                    topic_val: 10,//分值
                                    topic_answer: '',//正确答案
                                    options: [
                                        {
                                            opt: '',
                                            text: '',
                                            desc: '无'
                                        },
                                        {
                                            opt: '',
                                            text: '',
                                            desc: '无'
                                        }
                                    ]
                                }
                            } else {
                                this.$message({
                                    message: msg,
                                    type: 'warning'
                                })
                            }
                        }
                    )
                    .catch(
                        err => {
                            console.log(err);
                        }
                    )


            } else {
                // 弹窗
                if (confirm('请您先发布题库再添加题目')) {
                    this.dialogFormVisible = false;
                    // 跳转 “我的题库”
                    this.$router.push({
                        path: '/mytopicmanagement'
                    })
                }
            }
        },

        // 搜索题目1
        async addSearchFunc() {
            let keyword = this.query.name;
            await topicSearch({ keyword }).then(
                content => {
                    // console.log('列表1:', content)
                    let { code, msg, result } = content;
                    if (code == 200) {
                        this.tableData = result;
                        this.pageTotal = result.length;
                    }
                }
            )
        },

        // 搜索题目2 考试类型
        async addSearchFunc2() {
            let keyword = this.query.exam_type;
            if (keyword == "全部") {
                this.getData();
                this.getTotalNum();
                return;
            }
            await topicSearch({ keyword }).then(
                content => {
                    // console.log('列表2:', content)
                    let { code, msg, result } = content;
                    if (code == 200) {
                        this.tableData = result;
                        this.pageTotal = result.length;
                    }
                }
            )
        },

        // 选择题型时计算数量
        addTopicTypeFunc(type,lib_id) {
            let topic_type = type || this.form.topic_type;
            let topic_lib_id = lib_id ||  this.topic_lib_id;
            this.topicTypeTotalFunc(topic_lib_id, topic_type);
        },

        // 获取当前题库信息
        getCurrentTopicLibInfo() {
            // console.log("题库:", this.form.topic_lib_name);
            if (this.topicLibs.length == 0) {
                return false;
            }
            let arr = this.topicLibs.filter(item => {
                if (item.topic_lib_name == this.form.topic_lib_name) {
                    return item;
                }
            })
            // console.log(arr);
            this.currentTopicLibInfo = arr[0];
            // console.log('xx',this.form.topic_type ,arr[0].topic_lib_id);

            // 设置题目数量提示：
            this.addTopicTypeFunc(this.form.topic_type ,arr[0].topic_lib_id);
            
        },

        // 删除当前题目
        removeCurrentTopic(index) {
            // console.log({ index })
            if (this.form.options.length == 0) {
                return;
            }
            this.form.options.splice(index, 1);
        },

        // 获取已发布的题库
        async topicLibPublishFunc() {
            await getTopicLibPublish({}).then(content => {
                // console.log('1.0', content)
                let { code, result } = content;
                if (code == 200) {
                    if (result.length == 0) {
                        return;
                    }
                    this.topicLibs = result;
                    this.form.topic_lib_name = result[0].topic_lib_name;
                    this.topic_lib_id = result[0].topic_lib_id;
                    // 记录题型的数量
                    this.topic_single_count = result[0].topic_single_count;
                    this.topic_multi_count = result[0].topic_multi_count;
                    this.topic_judge_count = result[0].topic_judge_count;
                    this.currentTopicLibInfo = result[0];
                    this.isHasLib = true;
                    this.addTopicTypeFunc();
                }
            })
                .catch(
                    err => {
                        console.log(err);
                    }
                )
        },

        // 添加答案选项
        addOptionFunc() {
            let option = {
                opt: '',  //选项
                text: '', //答案内容
                desc: '', //答案解析
            }
            this.form.options.push(option);
        },
        // 获取题库题型数量
        async topicTypeTotalFunc(topic_lib_id, topic_type) {

            await topicTypeTotal({ topic_lib_id, topic_type }).then(content => {
                let { code, msg, total } = content;
                if (code == 200) {
                    // console.log('test',{total})
                    this.topic_current_num = total;
                    if(topic_type == "单选题"){
                        this.topic_total_num = this.topic_single_count;
                    }
                    else 
                    if(topic_type == "多选题"){
                        this.topic_total_num = this.topic_multi_count;
                    }
                    else 
                    if(topic_type == "判断题"){
                        this.topic_total_num = this.topic_judge_count;
                    }

                }
            })
        },
        // 获取 easy-mock 的模拟数据
        async getData(page_num = 1, page_size = 5) {

            await topicList({ page_num, page_size }).then(
                content => {
                    // console.log('题目列表:', content)
                    let { code, msg, result } = content;
                    if (code == 200) {
                        this.tableData = result;
                    }
                }
            )
                .catch(
                    err => {
                        console.log(err);
                    }
                )
        },

        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.getData(val);
        },

        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.getData(val);
        },




        // 获取总数量
        getTotalNum() {
            topicTotal({}).then(content => {
                let { code, result, total } = content;
                // console.log('总:', content)
                if (code == 200) {
                    this.pageTotal = total;
                }
            })
        },


        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },


        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => { });
        },


        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.topicRemoveArr = val;
        },

        // 删除题目
        async delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            // this.$message.error(`删除了${str}`);
            this.multipleSelection = [];

            // 执行删除
            for (let i = 0; i < this.topicRemoveArr.length; i++) {
                await topicRemove({ topic_id: this.topicRemoveArr[i].topic_id }).then(row => {
                    if (row.code == 200) {
                        // console.log(row);
                        let arr = this.tableData.filter(item => {
                            if (item.topic_id != this.topicRemoveArr[i].topic_id) {
                                return item;
                            }
                        })
                        this.tableData = arr;
                        this.$message({
                            message: '删除题目成功。',
                            type: 'success'
                        })
                    }
                })
            }
        },

        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
        },

        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },

        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },


        toggleSelection2(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },


        handleSelectionChange2(val) {
            this.multipleSelection = val;
        },


        // 多选操作(勾选正确答案)
        handleSelectionChange5(val) {
            if (val.length == 0) {
                return;
            }
            this.multipleSelection = val;
            let arr = [];
            val.forEach((item, i) => {
                arr[i] = item.opt;
            })
            // 记录题目正确答案
            let str = arr.sort().join('');
            this.form.topic_answer = str;
        },

        delAllSelection5() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },


    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
